package cn.itcast.controller;


import cn.itcast.domain.DingDan;
import cn.itcast.service.DingDanService;
import cn.itcast.service.WxPayService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

@RestController
@RequestMapping("/wxpay")
public class WxPayController {
    @Autowired
    private DingDanService dingDanService;

    @Autowired
    private WxPayService wxPayService;

    @GetMapping("/createNative")
    //前端返回的订单号
    public Map createNative(String orderId ){

        //当前的登陆用户
//        String username = SecurityContextHolder.getContext().getAuthentication().getName();

        DingDan dingDan = dingDanService.findById(orderId);
        if(dingDan!=null){
            //判断订单状态
            return  wxPayService.createNative(orderId,dingDan.getD_count(),"https://ceshi.easy.echosite.cn/wxpay/notify.do");

        }else{

            return null;
        }


    }

    /**
     * 回调结果，微信公众号返回的结果
     */
    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request){
        System.out.println("支付成功回调。。。。");
        try {
            InputStream inputStream = (InputStream)request.getInputStream();
            ByteArrayOutputStream outputStream=new ByteArrayOutputStream();

            byte[] buffer=new byte[1024];
            int len=0;
            while( ( len= inputStream.read(buffer) )!=-1   ){
                outputStream.write( buffer,0,len );
            }
            outputStream.close();
            inputStream.close();
            String result=new String( outputStream.toByteArray(),"utf-8" );
            System.out.println(result);
            wxPayService.notifyLogic(result);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //支付结果查询
    //消耗的内存大

    @GetMapping("/queryPayStatus")
    public Map queryPayStatus(String orderId){
        return  wxPayService.queryPayStatus(orderId);
    }

}
